package za.co.dylanjaneke.airdownloader.controller.data
{
	import com.adobe.cairngorm.persistence.restricted.statement.Statement;
	
	import flash.data.SQLConnection;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;
	import flash.net.Responder;
	import flash.utils.Timer;
	
	import mx.controls.Alert;
	
	import org.granite.reflect.visitor.handlers.VectorHandler;
	import org.granite.tide.Tide;
	
	import za.co.dylanjaneke.airdownloader.model.vo.DBVO;
	import za.co.dylanjaneke.airdownloader.model.vo.DownloadSiteVO;
	import za.co.dylanjaneke.airdownloader.model.vo.FileDownloadVO;
	import za.co.dylanjaneke.airdownloader.model.vo.LogEntryVO;
	import za.co.dylanjaneke.airdownloader.model.vo.SettingsVO;
	
	/**
	 * Author: Dylan Janeke.
	 */
	[Name("connectionManager")]
	public class ConnectionManager
	{
		private var connection:SQLConnection= new SQLConnection();
		
		private var mappedClasses:Array=
			[SettingsVO, DownloadSiteVO, LogEntryVO];
		
		public static function getInstance(): ConnectionManager
		{
			return Tide.getInstance().getContext().meta_getInstance("connectionManager") as ConnectionManager;
		}
		
		public function ConnectionManager()
		{
			start();
		}
		
		private function start(): void
		{
			var db:File= File.applicationDirectory.resolvePath("vicariousDownloader2.db");
			//db.deleteFile();
			connection.openAsync(db);
			connection.addEventListener(SQLEvent.OPEN, db_opened);
			connection.addEventListener(SQLErrorEvent.ERROR, error);
			connection.addEventListener(SQLErrorEvent.ERROR, error);
		}
		
		public function createStatement(): SQLStatement
		{
			var statement:SQLStatement= new SQLStatement();
			statement.sqlConnection= connection;
			return statement;
		}
		
		private function db_opened(e:SQLEvent): void
		{
			trace("Schema Update.");
			for each (var dbvo:Class in this.mappedClasses)
			{
				var instance:DBVO= new dbvo();
				trace("-> " + dbvo + " : " + instance.createQuery);
				execute(instance.createQuery);
			}
		}
		
		public function executeStatement(statement:SQLStatement, resultHandler:Function=null): void
		{
			if(resultHandler!=null)
				statement.addEventListener(SQLEvent.RESULT, resultHandler);
			statement.execute();
		}
		
		public function execute(query:String, resultHandler:Function=null): void
		{
			trace("execute) --> " + query +" , "+ resultHandler);
			var statement:SQLStatement= createStatement();
			
			if(resultHandler!=null)
				statement.addEventListener(SQLEvent.RESULT, resultHandler);
			
			statement.text= query;
			statement.execute();
		}
		
		private function error(e:SQLErrorEvent):void
		{
		    Alert.show(e.toString());
		}
	}
}